package com.ecar.api.oauth;

import net.sf.json.JSONObject;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;

import java.io.IOException;

/**
 * Created by admin on 2016/12/23.
 */
public class JsonOAuth2MessageConverter extends MappingJackson2HttpMessageConverter {

	@Override
	protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException,
																						HttpMessageNotWritableException {
		super.writeInternal(transformObject(object), outputMessage);
	}

	protected Object transformObject(Object object) {
		JSONObject json = new JSONObject();
		if (object instanceof OAuth2Exception) {
			OAuth2Exception o = (OAuth2Exception) object;
			json.put("code", 10000 + o.getHttpErrorCode());
			json.put("error", o.getOAuth2ErrorCode());
			json.put("error_description", o.getMessage());
		}
		return json;
	}
}
